// @ts-ignore
import {WechatyBuilder} from "wechaty";
import QRCode from "qrcode";
import {ChatGPTBot} from "./bot.js";
import {config} from "./config.js";
import * as ts from "typescript/lib/tsserverlibrary";
import Message = ts.server.protocol.Message;

const chatGPTBot = new ChatGPTBot();

const bot = WechatyBuilder.build({
    name: "wechat-assistant", // generate xxxx.memory-card.json and save login data for the next login
    puppet: "wechaty-puppet-wechat",
    puppetOptions: {
        uos: true
    }
});

async function handleWeChatMessage(chatGPTBot: any, message: any) {
    const text = await message.text();
    if (message.self()) {
        return; // 如果消息是机器人自己发送的，则跳过不处理
    }


    // 根据消息类型做出相应处理
    if (message.type()) {
        // 处理文字消息
        if (message.room()) {
            // 来自群聊
            if (await message.mentionSelf()) {
                if (message.text() !== "思考中，请稍等 . . .") {
                    await message.say("思考中，请稍等 . . .");
                }
                console.log("消息内容", message.type());
                try {
                    const {text} = message;
                    await chatGPTBot.onMessage(text, {isGeneratingResponse: true});
                } catch (e: any) {
                    console.error(e);
                    await message.say(e.message);
                }
            }
        } else {
            if (message.text() !== "思考中，请稍等 . . .") {
                await message.say("思考中，请稍等 . . .");
            }
            try {
                const {text} = message;
                console.log("消息内容", text);

                await chatGPTBot.onMessage(text, {isGeneratingResponse: true});
            } catch (e: any) {
                console.error(e);
                await message.say(e.message);
            }
        }
    }

}

// async function handleWeChatMessage(chatGPTBot: any, message: any) {
//   console.log("设置",message.text());
//   if (message.text() !== "思考中") {
//     await message.say("思考中");
//   }
//   if (message.self()) {
//     return; // 如果消息是机器人自己发送的，则跳过不处理
//   }
//   setTimeout(async () => {
//     await message.say("你好");
//   },1000)
//   const { text } = message;
//   await chatGPTBot.onMessage(text, { isGeneratingResponse: true });
// }
async function main() {
    const initializedAt = Date.now();
    bot
        .on("scan", async (qrcode: any, status: any) => {
            const url = `https://wechaty.js.org/qrcode/${encodeURIComponent(qrcode)}`;
            console.log(`Scan QR Code to login: ${status}\n${url}`);
        })
        .on("login", async (user: any) => {
            chatGPTBot.setBotName(user.name());
            console.log(`User ${user} logged in`);
            console.log(`私聊触发关键词: ${config.chatPrivateTriggerKeyword}`);
            console.log(`已设置 ${config.blockWords.length} 个聊天关键词屏蔽. ${config.blockWords}`);
            console.log(`已设置 ${config.chatgptBlockWords.length} 个ChatGPT回复关键词屏蔽. ${config.chatgptBlockWords}`);
        })
        .on("message", async (message: any) => {
            if (message.date().getTime() < initializedAt) {
                return;
            }
            if (message.text().startsWith("/ping")) {
                await message.say("pong");
                return;
            }
            try {

                await handleWeChatMessage(chatGPTBot, message);
            } catch (e) {
                console.error(e);
            }
        });
    try {
        await bot.start();
    } catch (e) {
        console.error(
            `⚠️ Bot start failed, can you log in through wechat on the web?: ${e}`
        );
    }
}

main();
